package test.my.com.myapplicationtest.retrofit_net;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import java.lang.ref.WeakReference;

import rx.Subscriber;

/**
 * Author : Cooper
 * Time : 2017/8/24  15:40
 * Description : 返回数据封装处理
 */
public abstract class SubscriberCallBack<T> extends Subscriber<ResponseEntity<T>> {

    private final int ERROR_CODE_NO_LOGIN = 1106; //用户未登录
    private final int ERROR_CODE_OTHER_LOGIN = 1510; //其他设备登录下线处理

    private ProgressControlInterface mProgressControlInterface;
    private WeakReference<Activity> mActivityWeakReference;
    private Dialog mLogginInvalidDialog;

    public SubscriberCallBack(Activity activity, ProgressControlInterface mProgressControlInterface) {
        this.mProgressControlInterface = mProgressControlInterface;
        this.mActivityWeakReference = new WeakReference<Activity>(activity);
    }

    @Override
    public void onNext(ResponseEntity responseEntity) {
        if (responseEntity.getResult() != null ) {
            onSuccess((T)responseEntity.getResult().getData());
            onSuccess(responseEntity.getResult());
        } else if(responseEntity.getError() != null){
            onFailure(responseEntity.getError());
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mProgressControlInterface.showProgress();
    }

    @Override
    public void onCompleted() {
        mProgressControlInterface.hideProgress();
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        ResponseEntity.ErrorBean errorBean = new ResponseEntity.ErrorBean();
        errorBean.setCode(100);
        errorBean.setMessage(e.getMessage());
        onFailure(errorBean);
    }

    /**
     * 提前检查错误信息，处理特殊错误code
     * @param errorBean
     */
//    private void handleParticularErrorMessage(ResponseEntity.ErrorBean errorBean) {
//        // 用户登录过期与被挤下线单独处理 无需回调error信息
//        if (errorBean.getCode() == ERROR_CODE_NO_LOGIN || errorBean.getCode() == ERROR_CODE_OTHER_LOGIN) {
//            final String message = errorBean.getMessage();
//            Activity activity = mActivityWeakReference.get();
//            if (mLogginInvalidDialog == null) {
//                mLogginInvalidDialog = userLoginDialog(activity, message, false, false);
//                if (activity != null && !activity.isFinishing() && !mLogginInvalidDialog.isShowing()) {
//                    mLogginInvalidDialog.show();
//                }
//            } else {
//                if (activity != null && !activity.isFinishing() && !mLogginInvalidDialog.isShowing()) {
//                    mLogginInvalidDialog.show();
//                }
//            }
//
//        }
//        onFailure(errorBean);
//    }

    //防止异步请求造成提示文本信息错乱
    static String false_login_content;
    static Dialog dialog_out;
    /**
     * 登录失效或者被挤掉线
     */
//    private static Dialog userLoginDialog(final Context context, String content, boolean iscenter, boolean flag) {
//        if (TextUtils.isEmpty(false_login_content))
//            false_login_content = content;
//        if (dialog_out == null)
//            dialog_out = new Dialog(context, R.style.myStyleDialog);
//        dialog_out.setCanceledOnTouchOutside(flag);
//        dialog_out.setCancelable(flag);
//        Window window = dialog_out.getWindow();
//        window.setContentView(R.layout.dialog_know);
//        WindowManager.LayoutParams params = window.getAttributes();
//        int widthPixels = context.getResources().getDisplayMetrics().widthPixels;
//        params.width = widthPixels / 10 * 8;
//        window.setAttributes(params);
//        TextView tv_msg = (TextView) window.findViewById(R.id.tv_msg);
//        if (iscenter) {
//            tv_msg.setGravity(Gravity.CENTER);
//        } else {
//            tv_msg.setGravity(Gravity.NO_GRAVITY);
//        }
//        if (false_login_content.equals(content)) {
//            tv_msg.setText(content);
//        } else {
//            tv_msg.setText(false_login_content);
//        }
//        TextView confirm = (TextView) window.findViewById(R.id.confirm);
//        confirm.setText("重新登录");
//        confirm.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog_out.dismiss();
//                false_login_content = "";
//                SharedPreferenceUtil.putUserPreferences("isLogin", false);
//                if (null == context || ((Activity) context).isFinishing()) {
//                    return;
//                }
//                // ========== 获得当前Activity名字 ===========
//                ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//                ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//                String className = cn.getClassName();
//                Class clazz = null;
//                try {
//                    clazz = Class.forName(className);
//                } catch (ClassNotFoundException e) {
//                    e.printStackTrace();
//                }
//                /** 不是登陆界面  就跳转到登陆界面 */
//                if (!className.equals(UserRegistLoginGetSmsActivity.class.getName())) {
//                    if (!className.equals(MainActivity.class.getName())) {
//                        if (clazz != null) {
//                            AppManager.getAppManager().findFinishActivity(clazz);
//                        }
//                    }
//                    SharedPreferenceUtil.getSpInstance(context).edit().clear().commit(); // 清除数据
//                    ZhuanBeiApplication.getInstance().removeJPushAlias(); // 删除极光别名
//                    ZhuanBeiApplication.getInstance().removeBuglyCrashReportUserId(); // 删除Bugly的Userid
//                    context.startActivity(new Intent(context, UserRegistLoginGetSmsActivity.class));
//                }
//            }
//        });
//        return dialog_out;
//    }


    /**
     * 直接获取返回结果
     * @param response
     */
    protected abstract void onSuccess(T response);

    /**
     * 需要返回code
     * @param response
     */
    protected void onSuccess(ResultBean<T> response){};

    protected abstract void onFailure(ResponseEntity.ErrorBean errorBean);


}
